package com.daqian.chance.example.web.modules.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daqian.chance.common.constant.WebCommonConstant;
import com.daqian.chance.core.exception.ServiceException;
import com.daqian.chance.core.util.MD5Util;
import com.daqian.chance.example.web.modules.member.mapper.MemberMapper;
import com.daqian.chance.example.web.modules.member.po.dto.MemberDTO;
import com.daqian.chance.example.web.modules.member.po.entity.Member;
import com.daqian.chance.example.web.modules.member.service.IMemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 用户-信息 服务实现类
 * </p>
 * @author daqian
 * @since 2019-07-25
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Override
    public PageInfo<Member> page(MemberDTO memberDTO) {
        // 开启分页
        PageHelper.startPage(memberDTO.getPageNum(), memberDTO.getPageSize());
        List<Member> memberList = super.list(null);
        // 清除分页
        PageHelper.clearPage();
        return new PageInfo<>(memberList);
    }

    /**
     * 登录
     * @param phone
     * @param loginPwd
     * @param session
     */
    @Override
    public Member login(String phone, String loginPwd, HttpSession session) {
        Assert.notEmpty(phone, "手机不可为空");
        Assert.notEmpty(loginPwd, "密码不可为空");
        Member member = this.getOne(new QueryWrapper<Member>().eq("phone", phone));
        Assert.notNull(member, "用户不存在");
        if (!MD5Util.encrypt(loginPwd).equals(member.getLoginPwd())) {
            throw ServiceException.msg("手机或密码错误");
        }

        // 登录成功，保存登录用户信息到session中
        session.setAttribute(WebCommonConstant.LOGIN_USER, member);
        return member;
    }

    /**
     * 获取当前登录用户信息
     * @param session
     * @return
     */
    @Override
    public Member getLoginUser(HttpSession session) {
        return (Member) session.getAttribute(WebCommonConstant.LOGIN_USER);
    }

}
